﻿using AutoMapper;
using JTTD.DataBase;
using JTTD.DataBase.Model.CompanyUserInfo;
using JTTD.Domain.Dtos;
using JTTD.Domain.IService;
using JTTD.Domain.Units;
using System;
using System.Threading.Tasks;
using JTTD.Common.Enum;
using JTTD.Domain.Dtos.CompanyUserInfo.Request;
using Microsoft.EntityFrameworkCore;
using JTTD.Domain.Dtos.CompanyUserInfo.Response;
using System.Collections.Generic;
using System.Linq;
using JTTD.Common.Helper;

namespace JTTD.Domain.Service
{
    /// <summary>
    /// 管理员/店家信息服务
    /// </summary>

    public class CompanyUserInfoService : ICompanyUserInfoService
    {

        private readonly JTTDContext _context;
        private readonly IMapper _mapper;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="mapper"></param>
        public CompanyUserInfoService(JTTDContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        /// <summary>
        /// 查询单个用户
        /// </summary>
        /// <param name="userNumber"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public async Task<ApiResult<InsertCompanyUserInfoRequestDto>> GetCompanyUserInfo(string userNumber, string passWord)
        {
            try
            {
                var user = await _context.CompanyUserInfoModels.FirstOrDefaultAsync(x => x.UserName == userNumber && x.Password == passWord);
                if (user != null && user.Id > 0)
                {
                    var info = _mapper.Map<InsertCompanyUserInfoRequestDto>(user);
                    info.Password = "";
                    return ApiResultUnit.Success(info);
                }
                else
                {
                    return ApiResultUnit.Error<InsertCompanyUserInfoRequestDto>("查询用户失败");
                }
            }
            catch (Exception ex)
            {
                return ApiResultUnit.Error<InsertCompanyUserInfoRequestDto>(ex);
            }
        }

        /// <summary>
        /// 店家入驻
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult<GetCompanyUserInfoDto>> InsertCompanyUser(InsertCompanyUserInfoRequestDto dto)
        {
            try
            {
                int existsCount = await _context.CompanyUserInfoModels.CountAsync(item => item.UserType == UserTypeEnum.Shop && (item.AuditStatus == AuditStatusEnum.AuditPass || item.AuditStatus == AuditStatusEnum.ToBeAudited) && item.Phone == dto.Phone.Trim());
                if (existsCount > 0)
                {
                    return new ApiResult<GetCompanyUserInfoDto> { IsSuccess = false, Message = $"当前手机号：{dto.Phone}已经注册店家" };
                }
                var info = _mapper.Map<CompanyUserInfoModel>(dto);
                info.UserType = UserTypeEnum.Shop;
                var user = _context.CompanyUserInfoModels.Add(info);
                await _context.SaveChangesAsync();
                var newInfo = _mapper.Map<GetCompanyUserInfoDto>(info);
                newInfo.Password = "";
                return ApiResultUnit.Success(newInfo);
            }
            catch (Exception ex)
            {
                return ApiResultUnit.Error<GetCompanyUserInfoDto>(ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResult<GetCompanyUserInfoDto>> GetCompanyUserInfoById(int id)
        {

            try
            {
                var user = await _context.CompanyUserInfoModels.FirstOrDefaultAsync(x => x.Id == id);
                if (user != null && user.Id > 0)
                {
                    user.Password = "";
                    var result = _mapper.Map<GetCompanyUserInfoDto>(user);
                    return ApiResultUnit.Success(result);
                }
                else
                    return ApiResultUnit.Error<GetCompanyUserInfoDto>("查询信息失败");
            }
            catch (Exception ex)
            {

                return ApiResultUnit.Error<GetCompanyUserInfoDto>(ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<ApiResult<GetCompanyUserInfoDto>> GetCompanyUserInfoById(int id, int userId)
        {

            try
            {
                var user = await _context.CompanyUserInfoModels.FirstOrDefaultAsync(x => x.Id == id);
                if (user != null && user.Id > 0)
                {
                    user.Password = "";
                    var result = _mapper.Map<GetCompanyUserInfoDto>(user);
                    var data = await _context.UserShopRelationModels.FirstOrDefaultAsync(x => x.UserId == userId && x.CompanyUserId == id);
                    result.Attention = data != null;
                    return ApiResultUnit.Success(result);
                }
                else
                    return ApiResultUnit.Error<GetCompanyUserInfoDto>("查询信息失败");
            }
            catch (Exception ex)
            {

                return ApiResultUnit.Error<GetCompanyUserInfoDto>(ex);
            }
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageResult<GetCompanyUserInfoDto>>> GetPageList(SearchCompanyUserInfoDto search)
        {

            var query = _context.CompanyUserInfoModels.Where(x => true && x.UserType == UserTypeEnum.Shop);
            if (!string.IsNullOrEmpty(search.UserName))
            {
                query = query.Where(x => x.UserName.Contains(search.UserName));
            }
            if (search.AuditStatus.HasValue)
            {
                query = query.Where(x => x.AuditStatus == search.AuditStatus.Value);
            }
            int count = await query.CountAsync();
            if (count > 0)
            {
                var list = await query.OrderBy(item => item.AuditStatus).ThenByDescending(item => item.CreateTime).Skip((search.PageIndex - 1) * search.PageSize).Take(search.PageSize).ToListAsync();
                foreach (var item in list)
                {
                    item.Password = "";
                }
                return new ApiResult<PageResult<GetCompanyUserInfoDto>>()
                {
                    IsSuccess = true,
                    Data = new PageResult<GetCompanyUserInfoDto>
                    {
                        Data = _mapper.Map<List<GetCompanyUserInfoDto>>(list),
                        PageIndex = search.PageIndex,
                        PageSize = search.PageSize,
                        TotalNum = count,
                        TotalPageNum = (count % search.PageSize) == 0 ? count / search.PageSize : count / search.PageSize + 1
                    }
                };
            }
            else
            {
                return new ApiResult<PageResult<GetCompanyUserInfoDto>>()
                {
                    Data = new PageResult<GetCompanyUserInfoDto>()
                    {
                        PageIndex = search.PageIndex,
                        PageSize = search.PageSize,
                        Data = new List<GetCompanyUserInfoDto>()
                    },
                    IsSuccess = true,
                    Message = "查询成功，暂无数据"
                };
            }

        }

        /// <summary>
        /// 微信公众号展示审核通过的店家列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageResult<GetShopUserDto>>> GetShopUserList(SearchShopRequestDto request)
        {
            try
            {
                var query = _context.CompanyUserInfoModels.Where(x => x.AuditStatus == AuditStatusEnum.AuditPass && x.UserType == UserTypeEnum.Shop);
                if (!string.IsNullOrWhiteSpace(request.ShopName))
                {
                    query = query.Where(item => item.UserName.Contains(request.ShopName.Trim()));
                }
                if (request.Floor > 0)
                {
                    query = query.Where(item => item.Floor == request.Floor);
                }
                if (!string.IsNullOrWhiteSpace(request.ShopType))
                {
                    query = query.Where(item => item.ShopType == request.ShopType);
                }
                int count = await query.CountAsync();
                if (count > 0)
                {
                    var list = await query.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToListAsync();
                    foreach (var item in list)
                    {
                        item.Password = "";
                    }
                    return new ApiResult<PageResult<GetShopUserDto>>()
                    {
                        IsSuccess = true,
                        Data = new PageResult<GetShopUserDto>
                        {
                            Data = _mapper.Map<List<GetShopUserDto>>(list),
                            PageIndex = request.PageIndex,
                            PageSize = request.PageSize,
                            TotalNum = count,
                            TotalPageNum = (count % request.PageSize) == 0 ? count / request.PageSize : count / request.PageSize + 1
                        }
                    };
                }
                else
                {
                    return new ApiResult<PageResult<GetShopUserDto>>()
                    {
                        Data = new PageResult<GetShopUserDto>()
                        {
                            PageIndex = request.PageIndex,
                            PageSize = request.PageSize,
                            Data = new List<GetShopUserDto>()
                        },
                        IsSuccess = true,
                        Message = "查询成功，暂无数据"
                    };
                }
            }
            catch (Exception ex)
            {
                StringHelper.AddLgoToTXT(ex.ToString());
                throw ex;
            }
        }

        /// <summary>
        /// 获取所有店家类型
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<string[]>> GetAllShopType()
        {
            var doc = XmlHelper.LoadXmlConfig("ShopTypeConfig.xml");
            var configs = XmlHelper.GetChildNode<ShopTypeDto>(doc.Elements().FirstOrDefault());
            return new ApiResult<string[]> { IsSuccess = true, Data = configs.Select(item => item.Node.Name).ToArray() };
        }

        /// <summary>
        /// 修改店铺密码
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> UpdateShopPwd(int shopId, UpdateShopPwdRequestDto dto)
        {
            try
            {
                var model = await _context.CompanyUserInfoModels.FindAsync(shopId);
                if (model == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "没有找到指定用户" };
                }
                if (dto.OldPwd != model.Password)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "旧密码错误" };
                }
                model.Password = dto.NewPwd;
                _context.CompanyUserInfoModels.Update(model);
                await _context.SaveChangesAsync();
                return new ApiResult<bool> { IsSuccess = true, Message = "操作成功" };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { IsSuccess = false, Message = "操作失败，" + ex.Message };
            }

        }

        /// <summary>
        /// 修改店铺信息
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> UpdateShopInfo(int shopId, UpdateShopInfoRequestDto dto)
        {
            try
            {
                var model = await _context.CompanyUserInfoModels.FindAsync(shopId);
                if (model == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "没有找到指定用户" };
                }
                model.UserName = dto.UserName;
                model.Phone = dto.Phone;
                model.HeadUrl = dto.HeadUrl;
                model.Floor = dto.Floor;
                model.Address = dto.Address;
                model.ShopType = dto.ShopType;
                model.ShopDetail = dto.ShopDetail;
                _context.CompanyUserInfoModels.Update(model);
                await _context.SaveChangesAsync();
                return new ApiResult<bool> { IsSuccess = true, Message = "操作成功" };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { IsSuccess = false, Message = "操作失败，" + ex.Message };
            }

        }

        /// <summary>
        /// 审核店家
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> ExamineShop(int shopId, int status)
        {
            try
            {
                var model = await _context.CompanyUserInfoModels.FindAsync(shopId);
                if (model == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "没有找到指定用户" };
                }

                int count = await _context.CompanyUserInfoModels.CountAsync(x => x.OpenId == model.OpenId && x.Phone == model.Phone && x.AuditStatus == AuditStatusEnum.AuditPass);
                if (count > 0)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "已存在正式商家" };
                }

                model.AuditStatus = (AuditStatusEnum)Enum.ToObject(typeof(AuditStatusEnum), status);
                _context.CompanyUserInfoModels.Update(model);
                await _context.SaveChangesAsync();
                return new ApiResult<bool> { IsSuccess = true, Message = "操作成功" };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { IsSuccess = false, Message = "操作失败，" + ex.Message };
            }
        }

        /// <summary>
        /// 重置店家密码
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> ResetShopPassword(int shopId)
        {
            try
            {
                var model = await _context.CompanyUserInfoModels.FindAsync(shopId);
                if (model == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "没有找到指定用户" };
                }
                model.Password = "000000";
                _context.CompanyUserInfoModels.Update(model);
                await _context.SaveChangesAsync();
                return new ApiResult<bool> { IsSuccess = true, Message = "操作成功" };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool> { IsSuccess = false, Message = "操作失败，" + ex.Message };
            }
        }


        /// <summary>
        /// 根据OpenID获取商户
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public async Task<ApiResult<GetCompanyUserInfoDto>> GetCompanyUserInfoByOpenId(string openId)
        {
            try
            {
                var user = await _context.CompanyUserInfoModels.FirstOrDefaultAsync(x => x.OpenId == openId);
                if (user != null && user.Id > 0)
                {
                    user.Password = "";
                    var result = _mapper.Map<GetCompanyUserInfoDto>(user);
                    return ApiResultUnit.Success(result);
                }
                else
                    return ApiResultUnit.Error<GetCompanyUserInfoDto>("查询信息失败");
            }
            catch (Exception ex)
            {
                StringHelper.AddLgoToTXT(ex.ToString());
                return ApiResultUnit.Error<GetCompanyUserInfoDto>(ex);
            }
        }

        /// <summary>
        /// 修改管理员密码
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="newPwd"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> UpdateAdminPassword(int userId, string newPwd)
        {
            try
            {
                var user = await _context.CompanyUserInfoModels.FirstOrDefaultAsync(x => x.Id == userId && x.UserType == UserTypeEnum.Admin);
                if (user == null)
                    return ApiResultUnit.Error<bool>("查询信息失败");

                user.Password = newPwd;
                _context.CompanyUserInfoModels.Update(user);
                await _context.SaveChangesAsync();
                return ApiResultUnit.Success(true);
            }
            catch (Exception ex)
            {
                return ApiResultUnit.Error<bool>(ex);
            }

        }

        /// <summary>
        /// 删除商户
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> DeleteCompanyUserInfo(int shopId)
        {
            try
            {
                var model = await _context.CompanyUserInfoModels.FirstOrDefaultAsync(x => x.Id == shopId && x.UserType == UserTypeEnum.Shop);
                if (model == null)
                {
                    return new ApiResult<bool> { IsSuccess = false, Message = "没有找到指定用户" };
                }
                _context.CompanyUserInfoModels.Remove(model);
                await _context.SaveChangesAsync();
                return ApiResultUnit.Success(true);
            }
            catch (Exception ex)
            {
                return ApiResultUnit.Error<bool>(ex.ToString());
            }
        }
    }
}
